package controllers

import (
	"beego/redis"
	"beego/tool"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"time"
)

type MainController struct {
	beego.Controller
}
type GetIpController struct {
	beego.Controller
}

func (c *MainController) Get() {
	redis.Init()
	ip := c.Ctx.Request.Header.Get("X-Real-ip")
	if redis.EXISTS(ip) == 0 {
		redis.LPUSH("ip", ip+" "+time.Now().String())
		redis.SetRedis([]byte(ip), ip, 10)
	}
	var r interface{}
	err := json.Unmarshal(tool.SendGetRQ("https://freeapi.ipip.net/"+ip), &r)
	if err != nil {
		fmt.Println(err)
	} else {
		location, _ := r.([]interface{})
		c.Data["Country"] = location[0]
		c.Data["Province"] = location[1]
	}
	c.Data["Nums"] = redis.LLEN("ip")
	c.Data["Ip"] = ip
	c.TplName = "index.tpl"
}
func (c *GetIpController) Get() {
	redis.Init()
	list := redis.LRANGE("ip", 0, redis.LLEN("ip"))
	c.Data["json"] = list
	c.ServeJSON()
}
